package com.zhiche.wms.service.certification.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.domain.mapper.certification.CertificationInfoMapper;
import com.zhiche.wms.domain.mapper.stock.SkuMapper;
import com.zhiche.wms.domain.mapper.stock.StockMapper;
import com.zhiche.wms.domain.model.certification.CertificationInfo;
import com.zhiche.wms.domain.model.sys.User;
import com.zhiche.wms.domain.model.sys.UserStorehouse;
import com.zhiche.wms.service.certification.CertificationService;
import com.zhiche.wms.service.sys.IUserService;
import com.zhiche.wms.service.sys.IUserStorehouseService;
import com.zhiche.wms.service.utils.CommonMethod;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: caiHua
 * @Description: 合格证实现类
 * @Date: Create in 10:10 2019/9/5
 */
@Service
public class CertificationServiceImpl extends ServiceImpl<CertificationInfoMapper, CertificationInfo> implements CertificationService {

    @Autowired
    private IUserService userService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private IUserStorehouseService iUserStorehouseService;

    @Override
    public List<String> receiveCertification (Map<String, String> param) {
        List<String> resultList;
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("未查询到登录用户");
        }
        //操作类型 Y 表示收取，N 表示发放
        String handleType = param.get("handleType");
        if (StringUtils.isEmpty(handleType)) {
            throw new BaseException("操作类型【handleType】不能为空！");
        }
        if (StringUtils.isEmpty(param.get("vin"))) {
            throw new BaseException("车架号【vin】不能为空！");
        }
        if (TableStatusEnum.STATUS_Y.getCode().equals(handleType)) {
            resultList = saveCertification(param.get("vin"), loginUser.getName());
        } else if (TableStatusEnum.STATUS_N.getCode().equals(handleType)) {
            if (StringUtils.isEmpty(param.get("certificationId"))) {
                throw new BaseException("参数【certificationId】不能为空！");
            }
            resultList = updateCertification(param.get("certificationId"), loginUser.getName());
        } else {
            throw new BaseException("操作类型【handleType】不合法！");
        }
        return resultList;
    }

    @Override
    public Page<CertificationInfo> queryCertificationPage (Page<CertificationInfo> page) {
        Map<String, Object> condition = page.getCondition();
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("未查询到登录用户");
        }

        EntityWrapper<CertificationInfo> certificationInfoEw = setCondition(condition);
        List<CertificationInfo> list = baseMapper.queryCertificationPage(page, certificationInfoEw);
        return page.setRecords(list);
    }

    @Override
    public List<CertificationInfo> exportCertificationPage (Page<CertificationInfo> page) {
        Map<String, Object> condition = page.getCondition();
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("未查询到登录用户");
        }
        EntityWrapper<CertificationInfo> certificationInfoEw = setCondition(condition);

        List<CertificationInfo> resultList = baseMapper.exportCertificationPage(certificationInfoEw);
        return resultList;
    }

    /**
     * 组装查询条件
     */
    private EntityWrapper<CertificationInfo> setCondition (Map<String, Object> condition) {
        EntityWrapper<CertificationInfo> certificationInfoEw = new EntityWrapper<>();
        if (!Objects.isNull(condition) && null != condition) {
            if (StringUtils.isNotEmpty((String) condition.get("certificatStatus"))) {
                certificationInfoEw.eq("certificat_status", condition.get("certificatStatus"));
            }
            if (condition.containsKey("receiveStartDate") && Objects.nonNull(condition.get("receiveStartDate"))) {
                certificationInfoEw.ge("receive_date", condition.get("receiveStartDate"));
            }
            if (condition.containsKey("receiveEndDate") && Objects.nonNull(condition.get("receiveEndDate"))) {
                certificationInfoEw.le("receive_date", condition.get("receiveEndDate"));
            }

            if (condition.containsKey("giveOutStartDate") && Objects.nonNull(condition.get("giveOutStartDate"))) {
                certificationInfoEw.ge("giveout_date", condition.get("giveOutStartDate"));
            }
            if (condition.containsKey("giveOutEndDate") && Objects.nonNull(condition.get("giveOutEndDate"))) {
                certificationInfoEw.le("giveout_date", condition.get("giveOutEndDate"));
            }
            if (condition.containsKey("isInbound") && Objects.nonNull(condition.get("isInbound"))) {
                if (TableStatusEnum.STATUS_Y.getCode().equals(condition.get("isInbound"))) {
                    certificationInfoEw.isNotNull("inboundDate");
                } else if (TableStatusEnum.STATUS_N.getCode().equals(condition.get("isInbound"))) {
                    certificationInfoEw.isNull("inboundDate");
                }
            }
            if (StringUtils.isNotEmpty((String) condition.get("vin"))) {
                String[] vins = CommonMethod.setVins((String) condition.get("vin"));
                certificationInfoEw.in("vin", Arrays.asList(vins)).or().like("vin", (String) condition.get("vin"));
            }
        }
        certificationInfoEw.orderBy("gmt_modified", false);
        return certificationInfoEw;
    }

    /**
     * 合格证发放
     *
     * @param certificationId 合格证id
     * @param name            登录用户
     */
    private List<String> updateCertification (String certificationId, String name) {
        List<String> reslut = new ArrayList<>();
        String[] ids = CommonMethod.setVins(certificationId);
        EntityWrapper<CertificationInfo> certificationEw = new EntityWrapper<>();
        certificationEw.in("id", Arrays.asList(ids));
        List<CertificationInfo> certificationInfos = baseMapper.selectList(certificationEw);
        if (CollectionUtils.isNotEmpty(certificationInfos)) {
            for (CertificationInfo certificationInfo : certificationInfos) {
                StringBuffer sb = new StringBuffer();
                if (certificationInfo.getCertificatNum() < 1) {
                    sb.append("该合格证已经被:").append(certificationInfo.getGiveoutUser()).append(":").append("发放过，无需再次发放！");
                    reslut.add(sb.toString());
                    continue;
                }
                CertificationInfo updateParam = new CertificationInfo();
                updateParam.setCertificatNum(certificationInfo.getCertificatNum() - 1);
                updateParam.setGiveoutUser(name);
                updateParam.setGiveoutDate(new Date());
                updateParam.setId(certificationInfo.getId());
                updateParam.setCertificatStatus(TableStatusEnum.STATUS_30.getCode());
                updateParam.setGmtModified(new Date());
                baseMapper.updateById(updateParam);
            }
        }
        return reslut;
    }

    /**
     * 领取
     *
     * @param vin 车架号
     */
    private List<String> saveCertification (String vin, String loginName) {
        List<String> reslut = new ArrayList<>();
        String[] vins = CommonMethod.setVins(vin);
        for (String vinStr : vins) {
            StringBuffer sb = new StringBuffer();
            CertificationInfo queryParam = new CertificationInfo();
            queryParam.setVin(vinStr);
            CertificationInfo certificationInfo = baseMapper.selectOne(queryParam);
            if (null != certificationInfo) {
                sb.append("车架号:").append(vinStr).append(":").append("合格证已经收取，请重新输入！");
                reslut.add(sb.toString());
                continue;
            }
            // 查询库存id
            Long stockId = stockMapper.queryMaxStockId(vinStr);
            CertificationInfo insertParam = new CertificationInfo();
            insertParam.setVin(vinStr);
            insertParam.setReceiveDate(new Date());
            insertParam.setReceiveUser(loginName);
            insertParam.setCertificatNum(1);
            insertParam.setCertificatStatus(TableStatusEnum.STATUS_20.getCode());
            if (null != stockId) {
                insertParam.setStockId(stockId);
            }
            baseMapper.insert(insertParam);
        }
        return reslut;
    }
}
